package com.leo.chapter06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 下载图片和渲染文字两个步骤并发执行
 * @author xuexiaolei
 * @version 2017年10月15日
 */
public class FutureRenderer {
    private final ExecutorService exec = Executors.newFixedThreadPool(10);

    void renderPage(CharSequence source){
        //下载图片
        final ImageInfo[] imageInfos = scanForImageInfo(source);
        Callable<List<ImageData>> task = new Callable<List<ImageData>>() {
            @Override public List<ImageData> call() throws Exception {
                List<ImageData> result =  new ArrayList<>();
                for (ImageInfo imageInfo : imageInfos)
                    result.add(imageInfo.downloadImage());
                return result;
            }
        };
        Future<List<ImageData>> future = exec.submit(task);

        //渲染文字
        renderText(source);

        //渲染图片
        try {
            List<ImageData> imageData = future.get();
            for (ImageData data : imageData)
                renderImage(data);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();//设置线程的中断状态
            future.cancel(true);//由于不需要结果，因此取消状态
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void renderImage(ImageData data) {
        System.out.println("正在渲染图片");
    }

    private ImageInfo[] scanForImageInfo(CharSequence source) {
        return new ImageInfo[]{};
    }

    private void renderText(CharSequence source) {
        System.out.println("正在渲染文字");
    }

    class ImageData{}
    class ImageInfo{
        public ImageData downloadImage(){
            System.out.println("下载图片中");
            try {
                Thread.sleep(1000);//很浪费时间的
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new ImageData();
        }
    }
}
